﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Forms;
using WpfApplication1.tools;
using System.Runtime.InteropServices;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        cPencil pencil = new cPencil();
        cLine line = new cLine();
        bool colorPick = false;

        cEraser eraser = new cEraser();
        //FrameworkElement selectedVisual;
        //Point lastMouseClick;

        public MainWindow()
        {
            InitializeComponent();
            pencil.brushColor = ColorPicker.SelectedColor;
            eraser.brushColor = Colors.White;
            line.brushColor = ColorPicker.SelectedColor;
            penRect.Fill = new SolidColorBrush(pencil.brushColor);
            eraserRect.Fill = new SolidColorBrush(eraser.brushColor);
            ImageTabs.SelectionChanged += new SelectionChangedEventHandler(ImageTabs_SelectionChanged);
            var view = CollectionViewSource.GetDefaultView(ImageTabs.Items);
            view.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(view_CollectionChanged);
        }

        void ImageTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                LayerGrid.Children.Clear();
                LayerGrid.RowDefinitions.Clear();
                if ((ClosableTabItem)ImageTabs.SelectedItem != null)
                {
                    foreach (Canvas layer in ((ClosableTabItem)ImageTabs.SelectedItem).Layers)
                    {
                        double ratio = 50 / layer.Height < 50 / layer.Width ? 50 / layer.Height : 50 / layer.Width;
                        ((TransformGroup)layer.LayoutTransform).Children[0] = new ScaleTransform(ratio, ratio);
                        RowDefinition newRow = new RowDefinition();
                        newRow.Height = new GridLength(60);
                        LayerGrid.RowDefinitions.Add(newRow);
                        LayerGrid.Children.Add(layer);
                        Grid.SetRow(layer, LayerGrid.RowDefinitions.IndexOf(newRow));
                    }
                }
            }
            catch { } 
        }

        void view_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            try
            {
                if (ImageTabs.Items.Count == 0)
                {
                    ImageTabs.Visibility = System.Windows.Visibility.Hidden;
                }
            }
            catch { }
        }

        private void New_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                NewFileConfigurationWindow newFileWindow = new NewFileConfigurationWindow();
                newFileWindow.SelectionFinnished.Click += new RoutedEventHandler(SelectionFinnished_Click);
                newFileWindow.Owner = this;
                newFileWindow.Show();
            }
            catch { }
        }

        void SelectionFinnished_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                NewFileConfigurationWindow parent = (NewFileConfigurationWindow)((Grid)((System.Windows.Controls.Button)sender).Parent).Parent;
                if (parent.DesiredWidth.Text == "" || parent.DesiredHeight.Text == "" || parent.DesiredName.Text == "")
                {
                    parent.GuidanceMessage.Text = "You have entered some invalid arguments";
                }
                else
                {
                    CreateTab(parent.DesiredName.Text, Convert.ToInt32(parent.DesiredHeight.Text), Convert.ToInt32(parent.DesiredWidth.Text));
                    ImageTabs.Visibility = System.Windows.Visibility.Visible;
                    infotextblock.Text = fileInformation();
                    parent.Close();
                }
            }
            catch { }
        }

        #region tabFunctionality
        private void CreateTab(String tabName, int Height, int Width)
        {
            try
            {
                ClosableTabItem item = new ClosableTabItem(tabName);
                attachCanvasEvents(item.getImageViewport());
                item.getImageViewport().Height = Height;
                item.getImageViewport().Width = Width;
                ImageTabs.Items.Add(item);
                ImageTabs.SelectedItem = item;
            }
            catch { }
        }

        private void OpenImageInTab(string path)
        {
            try
            {
                ClosableTabItem newTab = new ClosableTabItem(path.Split('\\').Last().ToString(), CreateImage(path));
                newTab.Loaded += new RoutedEventHandler(newTab_Loaded);
                attachCanvasEvents(newTab.getImageViewport());
                ImageTabs.Items.Add(newTab);
            }
            catch { }
        }

        void newTab_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ImageTabs.SelectedItem = (ClosableTabItem)sender;
            }
            catch { }
        }

        private void attachCanvasEvents(Canvas canvas)
        {
            try
            {
                canvas.MouseDown += new MouseButtonEventHandler(canvas_MouseDown);
                canvas.MouseUp += new MouseButtonEventHandler(canvas_MouseUp);
                canvas.MouseMove += new System.Windows.Input.MouseEventHandler(canvas_MouseMove);
            }
            catch { }
        }

        //private void CreateTabFromImage(Image image)
        //{
        //    ClosableTabItem newTab = new 
        //}

        //void scrollViewerContent_MouseWheel(object sender, MouseWheelEventArgs e)
        //{
        //    throw new NotImplementedException();
        //}

        //private Canvas CreateBlankCanvas(int Height, int Width)
        //{
        //    Canvas canvas = new Canvas();
        //    canvas.ClipToBounds = true;
        //    canvas.Height = Height;
        //    canvas.Width = Width;
        //    canvas.Background = Brushes.Cyan;
        //    canvas.MouseDown += new MouseButtonEventHandler(canvas_MouseDown);
        //    canvas.MouseUp += new MouseButtonEventHandler(canvas_MouseUp);
        //    canvas.MouseMove += new System.Windows.Input.MouseEventHandler(canvas_MouseMove);
        //    return canvas;
        //}
        #endregion

        //A method that executes when File->Open is selected
        //The method opens up a dialog window where the user can select image to open
        //Once the selection is compleated a new image is created and nicely fitted in a new tab in the application
        private void Open_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Open a dialog window for file selection
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    //Check if a selection is made
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        OpenImageInTab(ofd.FileName);
                        ImageTabs.Visibility = System.Windows.Visibility.Visible;
                        //infotextblock.Text = fileInformation();
                    }
                }
            }
            catch { }
        }

        

        //private void OpenFileInNewTab(String path)
        //{
        //    CreateTabFromImage(CreateImage(path));
        //}

        void FileName_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (((CloseableHeader)sender).close)
                {
                    ImageTabs.Items.Remove(((ClosableTabItem)((CloseableHeader)sender).Parent));
                }
            }
            catch { }
        }

        void FileName_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (e.MiddleButton == MouseButtonState.Pressed)
                {
                    ((CloseableHeader)sender).close = true;
                }
            }
            catch { }
        }

        private void AddLayer(Canvas canvas)
        {
            try
            {
                Image i = new Image();
                i.Source = ((Image)canvas.Children[0]).Source;
                double ratio = 56 / i.Source.Height < 56 / i.Source.Width ?
                    56 / i.Source.Height : 56 / i.Source.Width;
                Canvas c = new Canvas();
                c.RenderTransform = new ScaleTransform(ratio, ratio);
                System.Windows.Controls.Label layerName = new System.Windows.Controls.Label();
                c.Children.Add(i);
                RowDefinition rd = new RowDefinition();
                rd.Height = new GridLength(60);
                LayerGrid.RowDefinitions.Add(rd);
                layerName.Content = "layer " + LayerGrid.RowDefinitions.Count;
                LayerGrid.Children.Add(c);
                LayerGrid.Children.Add(layerName);
                Grid.SetRow(c, LayerGrid.RowDefinitions.Count - 1);
                Grid.SetColumn(layerName, 1);
                Grid.SetRow(layerName, LayerGrid.RowDefinitions.Count - 1);
            }
            catch { }
            
        }
        //A method that creates a bitmap from a filepath and puts it in an image
        private Image CreateImage(String path)
        {
            Image image = new Image();
            try
            {
                BitmapImage bitmap = new BitmapImage(new Uri(path));
                image.Source = bitmap;
                image.Height = bitmap.Height;
                image.Width = bitmap.Width;
                image.Stretch = Stretch.Fill;
                TransformGroup tg = new TransformGroup();
                tg.Children.Add(new ScaleTransform());
                tg.Children.Add(new RotateTransform());
                tg.Children.Add(new TranslateTransform());
                tg.Children.Add(new SkewTransform());
                image.RenderTransform = tg;
            }
            catch { }
            //image.MouseWheel += new MouseWheelEventHandler(selectedVisual_MouseWheel);
            //image.MouseMove += new System.Windows.Input.MouseEventHandler(image_MouseMove);
            //image.MouseRightButtonDown += new MouseButtonEventHandler(image_MouseRightButtonDown);
            return image;
        }

        //void image_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    Image i = (Image)sender;
        //    lastMouseClick = e.GetPosition(i);
        //}

        //void image_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        //{
        //    if (e.RightButton == MouseButtonState.Pressed)
        //    {
        //        Image i = (Image)sender;
        //        Point mouseCurrentLocation = e.GetPosition(i);
        //        TranslateTransform translation = (TranslateTransform)((TransformGroup)((Image)sender).RenderTransform).Children[2];
        //        translation.X += mouseCurrentLocation.X - lastMouseClick.X;
        //        translation.Y += mouseCurrentLocation.Y - lastMouseClick.Y;
        //    }
        //}

        //void selectedVisual_MouseWheel(object sender, MouseWheelEventArgs e)
        //{
        //    if (e.LeftButton == MouseButtonState.Pressed &&
        //        ((ScaleTransform)((TransformGroup)((Image)sender).RenderTransform).Children[0]).ScaleX + e.Delta*0.001 > 0)
        //    {
        //        Image i = (Image)sender;
        //        Canvas c = (Canvas)i.Parent;
        //        ScaleTransform scale = (ScaleTransform)((TransformGroup)i.RenderTransform).Children[0];
        //        TranslateTransform translation = (TranslateTransform)((TransformGroup)i.RenderTransform).Children[2];
        //        translation.X += (i.Width * (scale.ScaleX + e.Delta * 0.001) - i.Width * scale.ScaleX) / 2;
        //        translation.Y += (i.Height * (scale.ScaleY + e.Delta * 0.001) - i.Height * scale.ScaleY) / 2;
        //        scale.ScaleX += e.Delta * 0.001;
        //        scale.ScaleY += e.Delta * 0.001;
        //        c.Height = i.Height * scale.ScaleY;
        //        c.Width = i.Width * scale.ScaleX;
        //    }
        //}
/**********************************************************************************************************************************************/
/**********************************************************************************************************************************************/
/**********************************************************************************************************************************************/
        //method which purpose to convert Windows.Controls.Image to System.Drawing.Image so it could be converted to BitmapImage
        //and then used as a Source for ImageColorPicker to identify the color of pixel.
        System.Windows.Media.ImageSource ConvertDrawingImageToWPFImage()
        {
            System.Windows.Media.ImageSource WpfBitmap = null ;
            try
            {
                System.Windows.Controls.Image img = new System.Windows.Controls.Image();

                //convert System.Drawing.Image to WPF image
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(controlImageToDrawingImage());
                IntPtr hBitmap = bmp.GetHbitmap();
                WpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }
            catch { }

            return WpfBitmap;
        }

        System.Drawing.Image controlImageToDrawingImage()
        {
            System.Windows.Controls.Image img = (Image)((Canvas)((ScrollViewer)((ClosableTabItem)ImageTabs.SelectedItem).Content).Content).Children[0];
            MemoryStream ms = new MemoryStream();
            try
            {
                System.Windows.Media.Imaging.BmpBitmapEncoder bbe = new BmpBitmapEncoder();
                bbe.Frames.Add(BitmapFrame.Create(new Uri(img.Source.ToString(), UriKind.RelativeOrAbsolute)));
                bbe.Save(ms);
            }
            catch { }
            return System.Drawing.Image.FromStream(ms);
        }
/**********************************************************************************************************/
        public Color GetPixelColor(Visual visual, int x, int y)
        {
            return GetAverageColor(visual, new Rect(x, y, 1, 1));
        }

        public Color GetAverageColor(Visual visual, Rect area)
        {
            var bitmap = new RenderTargetBitmap(1, 1, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(
             new Rectangle
             {
                 Width = 1,
                 Height = 1,
                 Fill = new VisualBrush { Visual = visual, Viewbox = area }
             });
            var bytes = new byte[4];
            bitmap.CopyPixels(bytes, 1, 0);
            return Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]);
        }
/**********************************************************************************************************************************************/
        private struct POINT
        {
            public uint X;
            public uint Y;
        }

        [DllImport("gdi32")]
        private static extern int GetPixel(int hdc, int nXPos, int nYPos);
        [DllImport("user32")]
        private static extern int GetWindowDC(int hwnd);
        [DllImport("user32")]
        private static extern int GetCursorPos(out POINT lpPoint);
        [DllImport("user32")]
        private static extern int ReleaseDC(int hWnd, int hDC);

        private static SolidColorBrush GetPixelColor(Point point)
        {
            int lDC = GetWindowDC(0);
            int intColor = GetPixel(lDC, (int)point.X, (int)point.Y);
            //
            // Release the DC after getting the Color.-
            ReleaseDC(0, lDC);

            //byte a = (byte)( ( intColor >> 0x18 ) & 0xffL );
            byte b = (byte)((intColor >> 0x10) & 0xffL);
            byte g = (byte)((intColor >> 8) & 0xffL);
            byte r = (byte)(intColor & 0xffL);
            Color color = Color.FromRgb(r, g, b);
            return new SolidColorBrush(color);
        }
/**********************************************************************************************************************************************/
/**********************************************************************************************************************************************/
        void viewPort_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Grid sv = (Grid)((Canvas)sender).Parent;
                Image i = (Image)((Canvas)sender).Children[0];
                double ratio = sv.ActualHeight / i.Source.Height
                    < sv.ActualWidth / i.Source.Width ?
                    sv.ActualHeight / i.Source.Height : sv.ActualWidth / i.Source.Width;
                if (ratio < 1)
                {
                    i.Height = i.Source.Height * ratio;
                    i.Width = i.Source.Width * ratio;
                }
                else
                {
                    i.Height = i.Source.Height;
                    i.Width = i.Source.Width;
                }

                ((Canvas)sender).Height = i.Height;
                ((Canvas)sender).Width = i.Width;
                ((ScaleTransform)((TransformGroup)i.RenderTransform).Children[0]).CenterX = i.Width / 2;
                ((ScaleTransform)((TransformGroup)i.RenderTransform).Children[0]).CenterY = i.Height / 2;
            }
            catch { }
        }

        void FileName_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                TurnTabToAWindow(((ClosableTabItem)((CloseableHeader)((Grid)((System.Windows.Controls.Label)sender).Parent).Parent).Parent)).Show();
            }
            catch { }
        }

        Window TurnTabToAWindow(ClosableTabItem tabItem)
        {
            ImagePopUp window = new ImagePopUp();
            try
            {
                window.WindowTitle.Text = tabItem.Title;
                ScrollViewer sv = ((ScrollViewer)tabItem.Content);
                tabItem.Content = null;
                window.ActualContent.Children.Add(sv);
                window.Owner = this;
                window.MouseDoubleClick += new MouseButtonEventHandler(window_MouseDoubleClick);
                ((System.Windows.Controls.TabControl)tabItem.Parent).Items.Remove(tabItem);
            }
            catch { }
            return window;
        }

        void window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                ClosableTabItem newTab = TurnWindowToTab((ImagePopUp)sender);
                newTab.Title = ((ImagePopUp)sender).WindowTitle.Text;
                ((CloseableHeader)newTab.Header).FileName.MouseDoubleClick += new MouseButtonEventHandler(FileName_MouseDoubleClick);
                ImageTabs.Items.Add(newTab);
                ImageTabs.SelectedItem = newTab;
            }
            catch { }
        }

        ClosableTabItem TurnWindowToTab(ImagePopUp window)
        {
            ClosableTabItem newTab = new ClosableTabItem();
            try
            {
                ScrollViewer sv = ((ScrollViewer)((Grid)window.ActualContent).Children[0]);
                ((Grid)window.ActualContent).Children.Remove(sv);
                window.Close();
                newTab.Content = sv;
            }
            catch { }
            return newTab;
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (SaveFileDialog sfd = new SaveFileDialog())
                {
                    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        SaveCanvas((Canvas)sender, 96, sfd.FileName + ".png");
                }
            }
            catch { }
        }

        public void SaveCanvas(Canvas canvas, int dpi, string filename)
        {

            try
            {
                var rtb = new RenderTargetBitmap(
                        (int)canvas.ActualWidth, //width 
                        (int)canvas.ActualHeight, //height 
                        dpi, //dpi x 
                        dpi, //dpi y 
                        PixelFormats.Pbgra32 // pixelformat 
                        );
                rtb.Render(canvas);

                SaveRTBAsPNG(rtb, filename);
            }
            catch { }
        }

        private void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
        {
            try
            {
                var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
                enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));

                using (var stm = System.IO.File.Create(filename))
                {
                    enc.Save(stm);
                }
            }
            catch { }
        }

        #region TOOLBOX EVENT_CLICK
        private void Pencil_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                deselectToolbox();
                Pencil.IsChecked = !Pencil.IsChecked;
                pencil.selected = !pencil.selected;
            }
            catch { }
        }

        private void Fill_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                deselectToolbox();
                Fill.IsChecked = !Fill.IsChecked;
            }
            catch { }
//CODE TO BE
        }

        private void Text_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                deselectToolbox();
                Text.IsChecked = !Text.IsChecked;
            }
            catch { }
        }

        private void Eraser_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                deselectToolbox();
                eraser.selected = !eraser.selected;
                Eraser.IsChecked = !Eraser.IsChecked;
            }
            catch { }
        }

        private void Draw_Straight_Line_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                deselectToolbox();
                Line.IsChecked = !Line.IsChecked;
                line.selected = !line.selected;
            }
            catch { }
        }

        /*
         * methods suppose to enable/disable color picking function
         */
        private void colorPicker_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                deselectToolbox();
                colorPicker.IsChecked = !colorPicker.IsChecked;
                colorPick = !colorPick;
            }
            catch { }
        }
        #endregion

        private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //pencil.MouseDown(e.GetPosition((Canvas)sender));
                //eraser.MouseDown(e.GetPosition((Canvas)sender));
                //line.MouseDown(e.GetPosition((Canvas)sender));
                //Canvas c = (Canvas)((ScrollViewer)((ClosableTabItem)ImageTabs.SelectedItem).Content).Content;
                //sideRectangle.Background = new SolidColorBrush(GetPixelColor(c, (int)e.GetPosition(c).X, (int)e.GetPosition(c).Y));
                //SelectItem(sender, e);
                //colorPicking();
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    pencil.MouseDown(e.GetPosition((Canvas)sender));
                    line.MouseDown(e.GetPosition((Canvas)sender)); 
                    eraser.MouseDown(e.GetPosition((Canvas)sender));
                    //Canvas c = (Canvas)((ScrollViewer)((ClosableTabItem)ImageTabs.SelectedItem).Content).Content;
                    //sideRectangle.Background = new SolidColorBrush(GetPixelColor(c, (int)e.GetPosition(c).X, (int)e.GetPosition(c).Y));
                    //SelectItem(sender, e);
                    colorPicking();

                    if (Fill.IsChecked == true)
                    {
                        ((ClosableTabItem)ImageTabs.SelectedItem).getImageViewport().Background = new SolidColorBrush(ColorPicker.SelectedColor);
                        deselectToolbox();
                    }
                }
            }
            catch { }
        }

        /*
         *initializes cursors position and by using those points as a parameters passes it to getPixelColor and sideRectangle.Fill. 
         */
        private void colorPicking()
        {
            try
            {
                if (colorPick)
                {
                    POINT point;
                    GetCursorPos(out point);
                    Point pos = new Point(point.X, point.Y);
                    sideRectangle.Fill = GetPixelColor(pos);
                }
            }
            catch { }
        }

        private void fillCanvas()
        {
            try
            {
                POINT point;
                GetCursorPos(out point);
                Point pos = new Point(point.X, point.Y);
                SolidColorBrush color = GetPixelColor(pos);

                Image img = (Image)((Canvas)((ScrollViewer)((ClosableTabItem)ImageTabs.SelectedItem).Content).Content).Children[0];
                int canvasWidth = (int)img.Width;
                int canvasHeight = (int)img.Height;

                Point startPoint = pos;
            }
            catch { }
        }

        

        

        private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (e.ButtonState != MouseButtonState.Pressed)
                {
                    line.MouseUp();
                }
            }
            catch { }
        }

        private void canvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            try
            {
                //pencil.MouseMove(e.GetPosition((Canvas)sender), (Canvas)sender);
                //eraser.MouseMove(e.GetPosition((Canvas)sender), (Canvas)sender);
                colorPicking();
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    pencil.MouseMove(e.GetPosition((Canvas)sender), (Canvas)sender);
                    eraser.MouseMove(e.GetPosition((Canvas)sender), (Canvas)sender);
                    colorPicking();
                }
                if (e.LeftButton == MouseButtonState.Pressed && line.selected)
                {
                    line.MouseMove(e.GetPosition((Canvas)sender), (Canvas)sender);
                }
            }
            catch { }
        }

        /*
         * once one tool from toolbox is selected all the rest should be diselected.
         * One tool always has to be selected. (except on before selecting the first one, then there 
         * is nothing selected).
         */
        private void deselectToolbox()
        {
            try
            {
                pencil.selected = false;
                line.selected = false;
                colorPick = false;
                Pencil.IsChecked = false;
                Fill.IsChecked = false;
                Text.IsChecked = false;
                Eraser.IsChecked = false;
                Line.IsChecked = false;
                colorPicker.IsChecked = false;
                eraser.selected = false;

                Pencil.IsChecked = false;
                Fill.IsChecked = false;
                Text.IsChecked = false;
                Eraser.IsChecked = false;
                Line.IsChecked = false;

                colorPicker.IsChecked = false;
                Gradient.IsChecked = false;
                MagicWand.IsChecked = false;
                Marquee.IsChecked = false;
                MoveImgTool.IsChecked = false;
                ZoomToolbox.IsChecked = false;
                addLayerToolbox.IsChecked = false;
            }
            catch { }
        }

        private void Window_DragEnter(object sender, System.Windows.DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
                {
                    e.Effects = System.Windows.DragDropEffects.Move;
                }
            }
            catch { }
        }

        private void Window_Drop(object sender, System.Windows.DragEventArgs e)
        {
            try
            {
                string[] files = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop);
                if (files != null)
                {
                    foreach (string file in files)
                    {
                        try
                        {
                            OpenImageInTab(file);
                        }
                        catch { }
                    }
                }
                if (ImageTabs.Items.Count > 0)
                {
                    ImageTabs.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch { }
        }

        #region File menu bar items event listeners
        /*
         * MENU ITEM EVENT HANDLER
         */
        private void OpenRecent_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Close_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void CloseAll_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void SaveAs_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         * one of many ways to close an application. Might need testing since simple .Close() method
         * call might not close completely and still leave something to run in the backgroud 
         * or don't realease all resources
         */
        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        #endregion

        #region Edit
        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Undo_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Redo_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Cut_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Copy_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Paste_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Stroke_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Transform_Click(object sender, RoutedEventArgs e)
        {

        }
        #endregion

        #region Image
        /*
         * MENU ITEM EVENT HANDLER
         */
        private void ImageSize_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void CanvasSize_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Rotate_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Crop_Click(object sender, RoutedEventArgs e)
        {

        }
        #endregion

        #region Layer
        /*
         * MENU ITEM EVENT HANDLER
         */
        private void NewLayer_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void DeleteLayer_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void MergeLayers_Click(object sender, RoutedEventArgs e)
        {

        }
        #endregion

        #region Help
        /*
         * MENU ITEM EVENT HANDLER
         */
        private void About_Click(object sender, RoutedEventArgs e)
        {

        }
        #endregion


        #region MORE TOOLBOX EVENT_CLICK
        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Gradient_Click(object sender, RoutedEventArgs e)
        {
            deselectToolbox();
            colorPicker.IsChecked = !colorPicker.IsChecked;
        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void MagicWand_Click(object sender, RoutedEventArgs e)
        {
            deselectToolbox();
            MagicWand.IsChecked = !MagicWand.IsChecked;
        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void Marquee_Click(object sender, RoutedEventArgs e)
        {
            deselectToolbox();
            Marquee.IsChecked = !Marquee.IsChecked;
        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void MoveImgTool_Click(object sender, RoutedEventArgs e)
        {
            deselectToolbox();
            MoveImgTool.IsChecked = !MoveImgTool.IsChecked;
        }

        /*
         * MENU ITEM EVENT HANDLER
         */
        private void ZoomToolbox_Click(object sender, RoutedEventArgs e)
        {
            deselectToolbox();
            ZoomToolbox.IsChecked = !ZoomToolbox.IsChecked;
        }
        #endregion

        /*
         *exported code for the sole purpose of firing even when it is suppose to be.
         *Problem which occured when doing this was that the color was not set to any on creation of the file
         *(prior it would take it on click on canvas event to get color from color picker.
         */
        private void ColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
        {
            if ((bool)Pencil.IsChecked || (bool)Line.IsChecked)
            {
                pencil.brushColor = ColorPicker.SelectedColor;
                line.brushColor = ColorPicker.SelectedColor;
                penRect.Fill = new SolidColorBrush(pencil.brushColor);
            }
            if ((bool)Eraser.IsChecked)
            {
                eraser.brushColor = ColorPicker.SelectedColor;
                eraserRect.Fill = new SolidColorBrush(eraser.brushColor);
            }
        }

        /*
         *extracted code from canvas_mouseDown event handler. This function has to accur only when we move slider
         *and no when we click on canvas.
         */
        private void ColorSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            pencil.brushThickness = (int)ColorSlider.Value;
            eraser.brushThickness = (int)ColorSlider.Value;
            line.brushThickness = (int)ColorSlider.Value;
        }

        /*
         * for testing purpose to prevent from always having a need to create new file by entering its name and parameters.
         */
        private void NewDummy_Click(object sender, RoutedEventArgs e)
        {
            CreateTab("dummy tab", 400, 400);
            ImageTabs.Visibility = System.Windows.Visibility.Visible;
            infotextblock.Text = fileInformation();
        }

        private string fileInformation()
        {
            ClosableTabItem tj = (ClosableTabItem)ImageTabs.SelectedItem;
            string info = string.Format("File name: {0} \nWidth: {1} \nHeight: {2}", tj.Title, tj.getImageViewport().Width, tj.getImageViewport().Height);
            return info;
            //"some text from some place for the testing purspose much longer than it suppoose to be orriginally";
        }

        private void addLayerToolbox_Click(object sender, RoutedEventArgs e)
        {
            deselectToolbox();
            addLayerToolbox.IsChecked = !addLayerToolbox.IsChecked;
            Rectangle rect = new Rectangle();
            rect.Width = ((ClosableTabItem)ImageTabs.SelectedItem).getImageViewport().Width;
            rect.Height = ((ClosableTabItem)ImageTabs.SelectedItem).getImageViewport().Height;
            rect.Fill = new SolidColorBrush(Colors.Black);
            LayerColorSlider.Value = rect.Opacity;
            ((ClosableTabItem)ImageTabs.SelectedItem).AddVisual(rect);
            ((ClosableTabItem)ImageTabs.SelectedItem).SetLastChild(rect);
        }

        private void LayerColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
        {
            if (ImageTabs.SelectedItem != null)
            {
                ((ClosableTabItem)ImageTabs.SelectedItem).ChangeLayerRectangleColor(
                    LayerColorPicker.SelectedColor);
            }
        }

        private void LayerColorSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (ImageTabs.SelectedItem != null)
            {
                try
                {
                    ((ClosableTabItem)ImageTabs.SelectedItem).ChangeOpacity(
                        LayerColorSlider.Value);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.InnerException);
                }
            }
        }
    }
}
